package cn.michael.dev.data.structure.linked.list;

import cn.michael.dev.entity.ListNode;

/**
 * Created by hufenggang on 2021/9/18.
 *
 * 单链表反转
 */
public class LinkedListReverse {

    /**
     * 递归算法实现单链表反转
     *
     * @param head
     * @return
     */
    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode newListNode = reverseList1(head);

        head.next.next = head;
        head.next = null;

        return newListNode;
    }

    /**
     * 递归算法实现单链表反转
     *
     * @param head
     * @return
     */
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }
}
